<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog=true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="{row}">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button size="small" type="primary">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 5, 10, 20]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 弹层 -->
      <el-dialog
        title="新增角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, addRole, delRole } from '@/api/setting'

export default {
  name: 'Settings',
  data() {
    return {
      // 弹层数据
      roleForm: {
        name: '',
        description: ''
      },
      showDialog: false,
      list: [], // 每页数据
      total: 0, // 数据总数
      pageParams: {
        page: 1, // 页码
        pagesize: 2 // 每页2条数据
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    // 删除角色
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        try {
          await delRole(id)
          // console.log('delRole', res)
          // 如果当前页面只剩下1条数据，就让页码-1
          if (this.list.length === 1) {
            this.pageParams.page--
            // 当页码值小于或者等于0，就将它的值修改为1
            if (this.pageParams.page <= 0) {
              this.pageParams.page = 1
            }
            this.loadRoles()// 重新渲染
          }
        } catch (err) {
          console.log('delRole', err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //  新增角色
    async doAdd() {
      try {
        await addRole(this.roleForm)
        // console.log('addRole', res)
        // 保存数据
        this.showDialog = false // 关闭弹层
        // 计算最大页码值，跳转到最后一页
        this.total++
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        this.pageParams.page = maxPage
        this.loadRoles() // 重新渲染数据
      } catch (err) {
        console.log('addRole', err)
      }
    },
    // 弹层确定按钮
    hSubmit() {
      // 1 兜底校验
      this.$refs.roleForm.validate(valid => {
        if (!valid) return // 校验失败
        this.doAdd() // 发送新增角色请求
      })
    },
    // 获取所有角色信息
    async loadRoles() {
      try {
        const { data: res } = await getRoles(this.pageParams)
        // console.log('getRoles', res)
        // 保存数据
        this.total = res.total
        this.list = res.rows
      } catch (err) {
        console.log('getRoles', err)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles() // 重新渲染数据
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles() // 重新渲染数据
    }
  }
}
</script>
